package com.example.stringbufferlogger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.stringbufferlogger.VO.PageResponse;
import com.example.stringbufferlogger.entity.LogRecord;
import com.example.stringbufferlogger.entity.ReplayLog;
import com.example.stringbufferlogger.mapper.LogRecordMapper;
import com.example.stringbufferlogger.service.LogRecordService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LogRecordServiceImpl extends ServiceImpl<LogRecordMapper, LogRecord> implements LogRecordService {

    private final LogRecordMapper logRecordMapper;

    public LogRecordServiceImpl(LogRecordMapper logRecordMapper) {
        this.logRecordMapper = logRecordMapper;
    }

    @Override
    public LogRecord getLogRecordByRequestId(String requestId) {
        QueryWrapper<LogRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("requestid", requestId);
        return logRecordMapper.selectOne(queryWrapper);
    }

    @Override
    public List<LogRecord> getAllLogRecords() {
        return logRecordMapper.selectList(null);
    }

    @Override
    public List<LogRecord> getLogRecordsByConditions(String requestId, String replayStatus) {
        QueryWrapper<LogRecord> queryWrapper = new QueryWrapper<>();
        // 如果 requestId 不为空，添加请求 ID 条件
        if (requestId != null && !requestId.isEmpty()) {
            queryWrapper.eq("requestid", requestId);
        }
        // 如果 replaystatus 不为空，添加其他条件，假设表中有对应字段 other_field
        if (replayStatus != null && !replayStatus.isEmpty()) {
            queryWrapper.eq("replaystatus", replayStatus);
        }
        return logRecordMapper.selectList(queryWrapper);
    }

    @Override
    public LogRecord getLogRecordWithSessionAttributesMap(String requestId) {
        return logRecordMapper.selectLogRecordWithSessionAttributes(requestId);
    }


    public PageResponse<LogRecord> recordPageResponse(String requestId, int pageNum, int pageSize) {
        Page<LogRecord> page = new Page<>(pageNum, pageSize);
        QueryWrapper<LogRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("requestid", requestId);
        Page<LogRecord> resultPage = logRecordMapper.selectPage(page, queryWrapper);

        return new PageResponse<>(
                (int) resultPage.getCurrent(),
                (int) resultPage.getSize(),
                resultPage.getTotal(),
                resultPage.getRecords()
        );
    }
}
